﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ScenarioFramework.Modules.DM.DataModel;

namespace ScenarioFramework.Portal.SF.Modules.DM.UserControls
{
    public partial class DocumentTemplateTree : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, System.EventArgs e)
        {
            tvDocuments.Nodes.Clear();
            XMLDocumentTemplate document = null;
            document = Global.dmDBHelper.GetDocumentTemplate("DocumentationRepository_1");


            XMLDocuments xmlDocuments = document.XMLDocuments;

            TreeNode root = new TreeNode();
            root.Text = "Archivio Documentazione";
            for (int i = 0; i < xmlDocuments.Count; i++)
            {
                XMLDocumentTemplate docInstance = (XMLDocumentTemplate)xmlDocuments[i];
                string sDocInstanceId = docInstance.Name;

                this.AddDocumentToTree(ref root, "root", sDocInstanceId, "DocumentationRepository");
            }

            this.tvDocuments.Nodes.Add(root);

        }
        private void AddDocumentToTree(ref TreeNode root, string sNode, string sDocumentId, string sTreeName)
        {
            XMLDocumentTemplate document = Global.dmDBHelper.GetDocumentTemplate(sDocumentId);

            bool bRet = ScenarioFramework.WAPI.Role.CheckGrant(document.XMLGrants, Page.User.Identity.Name, "VISIBLE");
            if (bRet)
            {
                XMLDocuments xmlDocuments = document.XMLDocuments;
                string sNodeName = document.Name.Replace(" ", "_");

                TreeNode node = new TreeNode();
                node.Text = document.Name;
                node.NavigateUrl = String.Format("DocumentDetails.aspx?DocumentId={0}", document.Name);
                                
                root.ChildNodes.Add(node);

                for (int i = 0; i < xmlDocuments.Count; i++)
                {
                    XMLDocumentTemplate docInstance = (XMLDocumentTemplate)xmlDocuments[i];

                    this.AddDocumentToTree(ref node, sNodeName, docInstance.Name, sTreeName);
                }
            }
        }
    }
}